package com.deyuanyun.pic.settings.service.msgtemplate;

import com.alibaba.fastjson.JSON;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.settings.controller.dto.BizMsgThresholdVO;
import com.deyuanyun.pic.settings.controller.dto.base.PipeScheduleVO;
import com.deyuanyun.pic.settings.domain.base.BizMsgUser;
import com.google.common.collect.Lists;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *  管道周期消息推送
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-08-10
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
public class PipeCyclePushMsg extends AbstractPushMsgTemplate {

    private static final Logger LOGGER = LoggerFactory.getLogger(PipeCyclePushMsg.class);

    public static final String SCHEDULE_VO = "scheduleVO";
    public static final String PIPE_SCHEDULE = "pipeSchedule";

    @Override
    public void doPushMsgData() {
        if(super.interfaceParam.isEmpty()) {// 没有参数的时候直接返回
            LOGGER.info("没有传入参数");
            return;
        }
        Map<String, Object> paramMap = super.interfaceParam;

        Object scheduleObj = paramMap.get(SCHEDULE_VO);
        Object pipeScheduleObj = paramMap.get(PIPE_SCHEDULE);
        if(scheduleObj == null || pipeScheduleObj == null) {
            if(LOGGER.isInfoEnabled())
                LOGGER.info("参数中有空值，不允许向下执行");
            return;
        }
        initializeBizMsgSends(pipeScheduleObj, scheduleObj);
    }

    /**
     * 设置需要显示的数据保存到list集合中
     * @param date
     * @param scheduleVO
     */
    private void setThreContent(LocalDate date, PipeScheduleVO scheduleVO) {
        LocalDate d = date.plusDays(scheduleVO.getAdvance());//当前任务的执行时间加上提前通知天数，为在x年-x月-日之前
        String year = d.getYear() + "";
        String month = d.getMonthOfYear() + "";
        String day = d.getDayOfMonth() + "";
        super.thresListCastString(Lists.newArrayList(year, month, day ,scheduleVO.getPipeLineName() ,scheduleVO.getBeginName(), scheduleVO.getEndName()));
    }


    /**
     * @param args 参数说明：
     * <pre>
     * arg[0]：为业务阀值实体信息，类型为：{@link BizMsgThresholdVO}<br />
     * arg[1]：为管道管段任务周期实体类，类型为：{@link PipeScheduleVO}
     * </pre>
     */
    @Override
    public void initializeBizMsgSends(Object... args) {
        BizMsgThresholdVO pipeScheduleVO = (BizMsgThresholdVO) args[0];
        PipeScheduleVO scheduleVO = (PipeScheduleVO) args[1];
        super.roleList = scheduleVO.getRoleIdList();
        String thresholdId = pipeScheduleVO.getId();
        String msgContent = pipeScheduleVO.getMsgContent();
        LocalDate date = new LocalDate();

        setThreContent(date, scheduleVO);//设置阀值list信息

        if (roleList != null && !roleList.isEmpty()) {
            Set<String> userIds = super.bizMsgThresholdService.queryUseIdByRoleIds(roleList); //用户id集合
            List<MsgQueue.BizMsgUserInfo> userInfos = new ArrayList<MsgQueue.BizMsgUserInfo>();
            for (String userId : userIds) {
                String nowDateStr = date.toString("yyyyMMdd");
                String updateRemark = thresholdId + scheduleVO.getPipeLineId() + scheduleVO.getBeginMileageId() + scheduleVO.getEndMileageId() + nowDateStr;
                Map<String, Object> valiMap = new HashMap<String, Object>();
                //封装验证所需的map
                valiMap.put("bizMsgThresholdId", thresholdId);
                valiMap.put("pushFlagStr", updateRemark);
                valiMap.put("userId", userId);

                BizMsgUser bizMsgUser = new BizMsgUser();
                bizMsgUser.setCreateRemark("管道周期提醒任务");
                bizMsgUser.setCreateDate(new Date());
                if (StringUtils.isNotEmpty(msgContent))//消息内容不为空的时候设置到消息推送实体类
                    bizMsgUser.setMsgContent(msgContent);
                if (StringUtils.isNotEmpty(super.thresholdContent)) { //设置阀值内容
                    bizMsgUser.setThresholdContent(super.thresholdContent);
                }
                bizMsgUser.setUpdateRemark(updateRemark);
                bizMsgUser.setUserId(userId);
                bizMsgUser.setId(CommonUtil.getUUID());

                userInfos.add(msgQueue.new BizMsgUserInfo().setPushMsgTemplate(this).setValiMap(valiMap).setValid(true).setBizMsgUser(bizMsgUser));
            }
            if(!userInfos.isEmpty()) {
                //封装好需要发送的消息信息交给队列来推送消息
                MsgQueue.MsgInfo msgInfo = msgQueue.new MsgInfo().setBizMsgThresholdId(thresholdId)
                        .setThresholdSet(JSON.toJSONString(scheduleVO)).setRoleIds(roleList);
                msgQueue.addOperator(msgQueue.new PushMsgOperator(userInfos, msgInfo));
            }
        }
    }

    @Override
    public boolean valiIsPush(Map<String, Object> valiMap) {
        return super.bizMsgThresholdService.countPipeSchedule(valiMap);
    }
}
